﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Hanhud.Web.UI;
using Hanhud.Security;
using System.Text;

namespace Hanhud.Web.Pages.Membership
{
    public partial class LogIn : SitePage
    {
        public LogIn()
            : base("Membership", "LogIn")
        {
            this.Init += new EventHandler(LogIn_Init);
            //this.Load += new EventHandler(LogIn_Load);
        }

        void LogIn_Init(object sender, EventArgs e)
        {
        }

        void LogIn_Load(object sender, EventArgs e)
        {
        }

        protected void btnLogIn_Click(object sender, EventArgs e)
        {
            bool bValid = true;
            StringBuilder sb = new StringBuilder();

            string email = tbxEmail.Value.Trim();
            if (string.IsNullOrEmpty(email))
            {
                bValid = false;
                sb.AppendFormat(Hanhud.Web.Resources.Messages.RequiredField, "Email đăng nhập");
            }
            else if (!Hanhud.Utils.CHelper.IsValidEmail(email))
            {
                bValid = false;
                sb.AppendFormat(Hanhud.Web.Resources.Messages.InvalidInputField, "Email đăng nhập");
            }

            string password = tbxPassword.Value.Trim();
            if (string.IsNullOrEmpty(password))
            {
                bValid = false;
                sb.AppendFormat(Hanhud.Web.Resources.Messages.RequiredField, "Mật khẩu");
            }

            if (bValid)
            {
                // Kiem tra xem co' email nay duoc dang ky ko
                string userName = CMembership.GetUserNameByEmail(email);
                if (string.IsNullOrEmpty(userName))
                {
                    bValid = false;
                    sb.Append("Email hoặc mật khẩu không hợp lệ");
                }

                if (bValid && CMembership.ValidateUser(userName, password))
                {
                    // Co ton tai thanh vien nay, lay thong tin thanh vien
                    CPageContext.Current.User = CMembership.GetUser(userName, true);
                    CurrentUser.IsAuthenticated = true;

                    if (string.IsNullOrEmpty(Request.QueryString["returnUrl"]))
                    {
                        // Quay ve trang chur
                        Response.Redirect("~/Default.aspx");
                    }
                    else
                        Response.Redirect(Request.QueryString["returnUrl"]);
                }
                else
                {
                    bValid = false;
                    sb.Append("Email hoặc mật khẩu không hợp lệ");
                }
            }

            if (sb.Length > 0)
            {
                // Hien thi thong bao
                CMessageBox.Show(Page, sb.ToString());
            }
        }
    }
}